package net.paruo.google.gwt.study_meeting.user_control.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.paruo.google.gwt.study_meeting.user_control.client.DuplicateUserException;
import net.paruo.google.gwt.study_meeting.user_control.client.GreetingService;
import net.paruo.google.gwt.study_meeting.user_control.client.UserData;
import net.paruo.google.gwt.study_meeting.user_control.db.PMF;
import net.paruo.google.gwt.study_meeting.user_control.db.PersistentUserData;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	@Override
	public void createUser(UserData data) throws DuplicateUserException {
		String name = data.getName();
		String mailAddress = data.getMailAddress();
		String password = data.getPassword();

		if (isAlreadyExist(name)) {
			throw new DuplicateUserException("user already exists: " + name);
		}

		PersistentUserData storeData = new PersistentUserData();
		storeData.setName(name);
		storeData.setMailAddress(mailAddress);
		storeData.setPassword(password);

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			pm.makePersistent(storeData);
		} finally {
			pm.close();
		}
	}

	private boolean isAlreadyExist(String name) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<PersistentUserData> list;

		Query query = pm.newQuery(PersistentUserData.class);
		query.setFilter("name == sname");
		query.declareParameters("String sname");
		list = (List<PersistentUserData>) query.execute(name);

		return !list.isEmpty();
	}

	@Override
	public List<UserData> searchUser(String userName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(PersistentUserData.class);
		query.setFilter("name.startsWith(sname)");
		query.declareParameters("String sname");
		List<PersistentUserData> list = (List<PersistentUserData>) query
				.execute(userName);

		ArrayList<UserData> userList = new ArrayList<UserData>();
		for (PersistentUserData data : list) {
			UserData userData = new UserData();
			userData.setName(data.getName());
			userData.setMailAddress(data.getMailAddress());
			userData.setPassword(data.getPassword());
			userList.add(userData);
		}
		return userList;
	}
}
